package dao.impl;

import dao.UserDao;
import entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import resultsetextractor.UserResultSetExtractor;
import rowmapper.UserRowMapper;

import java.util.List;

@Repository("userDao3")
public class UserDaoImpl3 implements UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void insert(User user) {
        String sql=new StringBuffer()
                .append("insert into t_user ")
                .append("    (username,password) ")
                .append("values ")
                .append("    (?,?) ")
                .toString();
        jdbcTemplate.update(sql,user.getUsername(),user.getPassword());
    }

    @Override
    public void deleteById(Integer id) {
        String sql=new StringBuffer()
                .append("delete from t_user ")
                .append("where id=? ")
                .toString();
        jdbcTemplate.update(sql,id);
    }

    @Override
    public void update(User user) {
        String sql=new StringBuffer()
                .append("update t_user ")
                .append("set username=?, ")
                .append("    password=? ")
                .append("where id=?")
                .toString();
        jdbcTemplate.update(sql,user.getUsername(),
                                user.getPassword(),
                                user.getId());
    }

    @Override
    public List<User> selectAll() {
        String sql=new StringBuffer()
                .append("select * ")
                .append("from t_user ")
                .toString();
        return jdbcTemplate.query(sql,new UserRowMapper());
    }

    @Override
    public User selectById(Integer id) {
        String sql=new StringBuffer()
                .append("select * ")
                .append("from t_user ")
                .append("where id=? ")
                .toString();
//        List<User> users=jdbcTemplate.query(sql,new UserRowMapper(),id);
//        return users.size()==0?null:users.get(0);
        return jdbcTemplate.query(sql,new UserResultSetExtractor(),id);
    }

}
